package com.crm.system.controller.contractManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.ESUtil;
import com.crm.model.entity.contractManager.CustomerContract;
import com.crm.model.entity.couponManager.Coupon;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.qo.contractManager.*;
import com.crm.model.qo.contractReviewManager.ContractReviewDetailQO;
import com.crm.model.vo.customerContractManager.*;
import com.crm.model.vo.returnMoney.CustFinanceProductOderVO;
import com.crm.system.service.contractManager.CustomerContractService;
import com.crm.system.service.couponManager.CouponService;
import com.crm.system.service.customerManager.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

/**
 * @author yincuimei
 * @Date 2021/3/12 10:04
 * 合同管理
 */
@RestController
@RequestMapping("/customerContract")
@Slf4j
public class CustomerContractController {

    @Value("${esurl}")
    public String ESurl;

    @Autowired
    private CustomerContractService customerContractService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CouponService couponService;


    /**
     * (超级管理员)合同管理--合同列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectAllCustomerContractList")
    public DataResponse selectAllCustomerContractList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                      @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                      @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                      @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                      CustomerContractQO customerContractQO//查询条件
    ){
        try{
            DhPageInfo<CustomerContractVO> customerProductVOList = customerContractService.selectCustomerContractVOList(customerContractQO,pageIndex,pageSize,sortName,sortOrder,"0");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerProductVOList);
        }catch(Exception e){
            log.error("合同列表 == customerContract selectAllCustomerContractList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * (普通管理员)合同管理--合同列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectNormalCustomerContractList")
    public DataResponse selectNormalCustomerContractList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                         @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                         @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                         @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                         CustomerContractQO customerContractQO//查询条件
    ){
        try{
            DhPageInfo<CustomerContractVO> customerProductVOList = customerContractService.selectCustomerContractVOList(customerContractQO,pageIndex,pageSize,sortName,sortOrder,"1");
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerProductVOList);
        }catch(Exception e){
            log.error("合同列表 == customerContract selectNormalCustomerContractList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * (普通用户)合同管理--合同列表
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectCustomerContractList")
    public DataResponse selectCustomerContractList(@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                   @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                                   @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                   @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                   @RequestParam(value="contractStatusMultiple",required = false) String contractStatusMultiple,
                                                   CustomerContractQO customerContractQO//查询条件
    ){
        try{
            if(!StringUtils.isBlank(contractStatusMultiple)){
                List<String> contractStatusList = JSONArray.parseArray(contractStatusMultiple, String.class);
                customerContractQO.setContractStatusList(contractStatusList);
            }
            DhPageInfo<CustomerContractVO> customerProductVOList = customerContractService.selectUserCustomerContractVOList(customerContractQO,pageIndex,pageSize,sortName,sortOrder);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerProductVOList);
        }catch(Exception e){
            log.error("合同列表 == customerContract selectCustomerContractList error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }


    /**
     * @Description: 查询单品合同列表
     * @Param: [pageIndex, pageSize, sortName, sortOrder, contractStatusMultiple, customerContractQO]
     * @Return: com.crm.common.model.DataResponse
     * @Author: lixq-f
     * @Date: 2021/6/17
    **/
    @PostMapping("/selectSingleContractList")
    public DataResponse selectSingleContractList(@RequestParam(value = "pageIndex", required = false, defaultValue = "1") Integer pageIndex,//页码
                                                 @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize,//分页大小
                                                 @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                                 @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc)
                                                 CustomerContractQO customerContractQO){
        DhPageInfo<CustomerContractVO> list = customerContractService
                .selectSingleContractList(customerContractQO, pageIndex, pageSize, sortName, sortOrder);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),list);
    }

    /**
     * 合同列表--查看
     * @param contractId ---合同ID
     * @author yincuimei
     * @return
     */
    @PostMapping("/selectCustomerContractById")
    public DataResponse selectCustomerContractById(@RequestParam(value="contractId",required = true)String contractId){
        try{
            CustomerContractDetailVO customerContractDetailVO = customerContractService.selectCustomerContractVODetail(contractId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerContractDetailVO);
        }catch(Exception e){
            log.error("合同详情 == customerContract selectCustomerContractById error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 合同列表--作废
     * @param contractId     ---合同ID
     * @param contractStatus ---合同作废状态
     * @author yincuimei
     * @return
     */
    @PostMapping("/cancelCustomerContract")
    public DataResponse cancelCustomerContract(@RequestParam(value="contractId")String contractId,@RequestParam(value="contractStatus")String contractStatus){
        JSONObject jsonObject = customerContractService.cancelCustomerContract(contractId,contractStatus);
        ESUtil.syncConctract(contractId,ESurl);
        if(jsonObject.containsKey("operateFlag")){
            if("disableCancel".equals(jsonObject.getString("operateFlag"))){
                return new DhResponse(ResponseCodeEnum.DISABLE_CANCEL_CONTRACT.getResponseCode());
            }else{
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
        }
        return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
    }

    /**
     * 合同详情--上传补充材料》只有审核处理结果为补充材料;合同状态为审核中的才可以上传
     * @author yincuimei
     * @return
     */
    @PostMapping("/uploadReplenishAnnex")
    public DataResponse uploadReplenishAnnex(CustomerContract customerContract,@RequestParam("file") MultipartFile file)
    {
        try{
            Boolean result = customerContractService.updateContractReplenishAnnex(customerContract,file);
            if(result){
                return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
            }
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }catch(Exception e){
            return new DhResponse(ResponseCodeEnum.SERVICE_ERROR.getResponseCode());
        }
    }

    /**
     * @Description:根据客户id获取联系人列表
     * @Param:  * @param customerId 客户id
     * @Author: luojie
     * @Date: 2021/3/15 18:48
     */
    @GetMapping("/selectContractListByCustomerId")
    public DataResponse selectContractListByCustomerId(@RequestParam("customerId") String customerId){
        try{
            List<CustomerContractVO> customerContractList =  customerContractService.selectContractListByCustomerId(customerId);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerContractList);
        }catch(Exception e){
            log.error("customerContract selectContractListByCustomerId error:", e);
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * @Description:添加/修改合同基本信息
     * @Param:  * @param body 合同以及相关信息参数
     * @Author: luojie
     * @Date: 2021/3/17 14:08
     */
    @PostMapping("/addContractInformation")
    public DataResponse addContractInformation(@RequestBody CustomerContractAddQO customerContractAddQO
/*                                               @RequestParam MultipartFile contractAnnex,
                                               @RequestParam MultipartFile reviewAnnex*/) throws ParseException, IOException {
        //修改合同条件是（合同未生效，且未回款，且审核未通过）
        if(!StringUtils.isBlank(customerContractAddQO.getContractId())&&(!customerContractAddQO.getContractStatus().equals("1")||!customerContractAddQO.getPaymentStatus().equals("0"))
            &&(!customerContractAddQO.getContractReviewStatus().equals("0")&&!customerContractAddQO.getContractReviewStatus().equals("1"))){
            return new DhResponse(ResponseCodeEnum.CONTRACT_CANNOT_EDITED.getResponseCode());
        }

        //客户id为空直接返回
        if(StringUtils.isBlank(customerContractAddQO.getCustomerId())/*||
                ((customerContractAddQO.getContractType().equals("1")||customerContractAddQO.getContractType().equals("2"))
                        &&(!StringUtils.isBlank(customerContractAddQO.getFollowRecordId())||!StringUtils.isBlank(customerContractAddQO.getOpportunityId())))*/){
            return new DhResponse(ResponseCodeEnum.PARAMETER_ERROR.getResponseCode());
        }
        //如果合同的支付方式为3:余额支付;4:转入额支付;5:余额＋转入额支付，则判断客户响应金额
        String paymentMethod = customerContractAddQO.getPaymentMethod();
        if(paymentMethod != null && !paymentMethod.equals("2")){
            //查询客户信息
            Customer customer = customerService.selectCustomerById(customerContractAddQO.getCustomerId());
            switch(paymentMethod){
                case "3":{
                    if(customer.getCustomerWallet()==null||(customer.getCustomerWallet()!=null&&customer.getCustomerWallet().compareTo(customerContractAddQO.getContractReceivables())==-1)){
                        return new DhResponse(ResponseCodeEnum.CONTRACT_INSUFFICIENT_BALANCE.getResponseCode());
                    }
                    break;
                }
                case "4":
                    if(customer.getCustomerShiftWallet()==null||(customer.getCustomerShiftWallet()!=null&&customer.getCustomerShiftWallet().compareTo(customerContractAddQO.getContractReceivables())==-1)){
                        return new DhResponse(ResponseCodeEnum.CONTRACT_INSUFFICIENT_BALANCE.getResponseCode());
                    }
                    break;
                case "5":
                    if(customer.getCustomerShiftWallet()!=null&&(customer.getCustomerWallet().add(customer.getCustomerShiftWallet()).compareTo(customerContractAddQO.getContractReceivables())==-1)){
                        return new DhResponse(ResponseCodeEnum.CONTRACT_INSUFFICIENT_BALANCE.getResponseCode());
                    }
                    break;
                default:
                    break;
            }

        }

        //判断优惠券是否还有剩余数量
/*        Coupon coupon = customerContractAddQO.getCoupon();
        if(coupon!=null){
            Coupon couponNew = couponService.selectCouponById(coupon.getChsCustomerCouponId());
            if(couponNew.getCouponCount()<=couponNew.getCouponUseCount()){
                return new DhResponse(ResponseCodeEnum.COUPON_HAS_EXPIRED.getResponseCode());
            }
        }*/

        //新增合同
        Boolean result = customerContractService.addContractInformation(customerContractAddQO);

        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.CONTRACT_CANNOT_SAVE.getResponseCode());
        }
    }

    /***
     * @Description:审核管理-更新合同详情
     * @Param:  * @param contractReviewDetailQO 更新合同对象
     * @Author: luojie
     * @Date: 2021/3/30 16:50
     */
    @PostMapping("/updateContractDetail")
    public DataResponse updateContractReviewDetail(@RequestBody ContractReviewDetailQO contractReviewDetailQO){
        //审核过的合同都可以修改保存
        //查询合同是否已经审核过
        CustomerContractDetailVO customerContractDetailVO = customerContractService.selectCustomerContractVODetail(contractReviewDetailQO.getContractId());
        if("2".equals(customerContractDetailVO.getContractReviewStatus())||"3".equals(customerContractDetailVO.getContractReviewStatus())){
            return new DhResponse(ResponseCodeEnum.CONTRACT_REVIEWED.getResponseCode());
        }
        Boolean result = customerContractService.updateContractReviewDetail(contractReviewDetailQO);
        ESUtil.syncConctract(contractReviewDetailQO.getContractId(),ESurl);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /***
     * @Description:根据合同id查询合同续费信息
     * @Param: contractId 合同id
     * @Author: luojie
     * @Date: 2021/4/15 16:45
     */
    @GetMapping("/selectContractRenewalInformation")
    public DataResponse selectContractRenewalInformation(@RequestParam("contractId") String contractId,
                                                         @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                                         @RequestParam(value = "pageSize", required = true) Integer pageSize){
        ContractRenewalVO contractRenewalVO = customerContractService.selectContractRenewalInformation(contractId,pageIndex,pageSize);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractRenewalVO);
    }

    /***
     * @Description:根据合同id查询合同信息(合同续费)
     * @Param:contractId 合同id
     * @Author: luojie
     * @Date: 2021/4/19 8:37
     */
    @GetMapping("/selectContractById")
    public DataResponse selectContractById(@RequestParam("contractId") String contractId){
        ContractRenewalAddVO customerContract = customerContractService.selectContractById(contractId);
        ESUtil.syncConctract(contractId,ESurl);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerContract);
    }

    /***
     * @Description:根据合同id查询合同合作开发人员
     * @Param:contractId 合同id
     * @Author: luojie
     * @Date: 2021/4/19 8:37
     */
    @GetMapping("/selectContractCoDeveloperById")
    public DataResponse selectContractCoDeveloperById(@RequestParam("contractId") String contractId){
        List<JSONObject> results= customerContractService.selectContractCoDeveloperById(contractId);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),results);
    }

    /***
     * @Description:根据合同编号查询合同续费信息
     * @Param: contractNumber 合同编号
     * @Author: luojie
     * @Date: 2021/6/1 14:44
     */
    @GetMapping("/selectContractByContractNumber")
    public DataResponse selectContractByContractNumber(@RequestParam("contractNumber") String contractNumber){
        ContractRenewalAddVO customerContract = customerContractService.selectContractByContractNumber(contractNumber);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),customerContract);
    }

    /***
     * @Description:查询未回款合同
     * @Param:
     * @Author: luojie
     * @Date: 2021/4/26 9:27
     */
    @GetMapping("/selectUnpaidContractList")
    public DataResponse selectUnpaidContract(){
        DhPageInfo<ContractUnpaidVO> contractUnpaidVOList = customerContractService.selectUnpaidContract();
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),contractUnpaidVOList);
    }

    /**
     * 更新
     * @param customerContractUpdateQO
     * @return
     */
    @PostMapping("/updateReviewFailedContract")
    public DataResponse updateReviewFailedContract(@RequestBody CustomerContractUpdateQO customerContractUpdateQO){
        Boolean result = customerContractService.updateReviewFailedContract(customerContractUpdateQO);
        ESUtil.syncConctract(customerContractUpdateQO.getContractId(),ESurl);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /***
     * @Description:查询合同类型为会员合同下会员产品列表
     * @Param:
     * @Author: luojie
     * @Date: 2021/8/3 16:34
     */
    @PostMapping("/getMemberOrNonMemberProductList")
    public DataResponse getMemberProductList(HttpServletRequest request,
                                               @RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                               @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                               @RequestParam(value = "sortName", required = false) String sortName,//排序列名字
                                               @RequestParam(value = "sortOrder", required = false) String sortOrder,//排序规则(asc/desc)
                                               @RequestParam(value = "orderId", required = false) String orderId, //订单id
                                               @RequestParam(value = "productCategories", required = false) String productCategories
    ) {

        if(!StringUtils.isBlank(orderId)){
            DhPageInfo<CustFinanceProductOderVO> list = customerContractService.getMemberProductList(pageIndex, pageSize, sortName, sortOrder, orderId, productCategories);
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), list);
        }else {
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode(), null);
        }

    }

    /***
     * @Description:合同联系人列表
     * @Param:customerId 客户id
     * @Param:auditStatus 合同联系人审核状态
     * @Param:onTheJobSituation 职业状态
     * @Author: luojie
     * @Date: 2021/9/2 9:24
     */
    @PostMapping("/getContractContactList")
    public DataResponse getContractContactList(HttpServletRequest request,@RequestParam(value = "pageIndex", required = true) Integer pageIndex,//页码
                                               @RequestParam(value = "pageSize", required = true) Integer pageSize,//分页大小
                                               @RequestParam(value="sortName",required = false) String sortName,//排序列名字
                                               @RequestParam(value="sortOrder",required = false) String sortOrder,//排序规则(asc/desc),
                                               @RequestParam(value = "customerId", required = false) String customerId,
                                                String auditStatus,
                                                String onTheJobSituation){
        DhPageInfo<ContractContactVO> contractContactVODhPageInfo = customerContractService.selectContractContactList(customerId, pageIndex, pageSize, sortName, sortOrder, auditStatus, onTheJobSituation);
        return  new DhResponse(ResponseCodeEnum.OK.getResponseCode(), contractContactVODhPageInfo);
    }


    /***
     * @Description:根据合同id更新合同联系人
     * @Param:CustomerContractUpdateQO
     * @Author: luojie
     * @Date: 2021/9/2 22:55
     */
    @PostMapping("/updateContractContactByContractId")
    public DataResponse updateContractContactByContractId(HttpServletRequest request,@RequestBody ContractContactUpdateQO customerContractUpdateQO){
        Boolean result =  customerContractService.updateContractContactByContractId(customerContractUpdateQO);
        if(result){
            return new DhResponse(ResponseCodeEnum.OK.getResponseCode());
        }else {
            return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
        }
    }

    /**
     * 合同的一些调整
     * @param contractNumber 合同编号
     * @param orderNumber 订单编号
     * @param customerName 客户名称
     * @param userName 用户名称
     * @param bs  1调整生效合同 2补全客户信息和登录人信息 3补全客户信息 4补全登录人信息
     * @return
     */
    @PostMapping("/adjustmentContract")
    public DataResponse adjustmentContract(@RequestParam(value = "contractNumber") String contractNumber,
                                               @RequestParam(value = "orderNumber") String orderNumber,
                                               @RequestParam(value="customerName") String customerName,
                                               @RequestParam(value="userName") String userName,
                                               @RequestParam(value="bs") String bs){
        String result = customerContractService.adjustmentContract(contractNumber,orderNumber,customerName,userName,bs);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),result);

    }
}


